import { GoodsChildrenFrag } from './goods.js';

const state = {
  /** @type {GoodsItem[]} */
  list: goods.map(item =>
    Object.assign(Object.create(item), { count: 0 }),
    goods,
  ),
  /** @type {number} */
  get count() {
    return R.compose( R.sum, R.pluck('count') )(this.list);
  },
  /** @type {number} */
  get price() {
    return R.compose(
      R.sum,
      R.map(R.compose( R.apply(R.multiply), R.props(['price','count']) ))
    )(this.list)
  },
}

const prog = {
  /** @type {HTMLDivElement} */
  get goodsListElem() {
    return document.querySelector('.goods-list');
  },
  /** @type {HTMLDivElement} */
  get carElem() {
    return document.querySelector('.footer-car');
  },
  /** @type {HTMLDivElement} */
  get payElem() {
    return document.querySelector('.footer-pay');
  },
  get badgeElem() {
    return document.querySelector('.footer-car-badge')
  },
  /** @type {HTMLSpanElement} */
  get totalElem() {
    return document.querySelector('.footer-car-total');
  }
};

function main() {
  const totalChangeEvent = new Event('totalchange');
  prog.goodsListElem.appendChild(
    GoodsChildrenFrag(() => dispatchEvent(totalChangeEvent), state.list)
  );
  addEventListener('totalchange', () => {
    prog.badgeElem.innerHTML = String(state.count);
    prog.totalElem.innerHTML = state.price.toFixed(2);
    const action = ['remove', 'add'][Number(0 < state.count)];
    prog.payElem.classList[action]('active');
    prog.carElem.classList[action]('active');
  });
}

main();
